package com.ruitu.mall_98_2.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyRefreshBaseFragment;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.utils.ClipboardUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.MD5Util;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.order.AfterSalesOrderActivity;
import com.ruitu.mall_98_2.order.MyAdvanceOrderActivity;
import com.ruitu.mall_98_2.order.MyGroupBookingActivity;
import com.ruitu.mall_98_2.order.MyOrderActivity;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.DataAdapter;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.User;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Service;
import com.ruitu.router_module.bean.product.Product;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MineFragment extends MyRefreshBaseFragment {
    private LinearLayout ll_user_head,//头像
            ll_waiting_pay,//代付款
            ll_waiting_send,//待发货
            ll_waiting_reciever,//待收货
            ll_waiting_comment,//待评论
            ll_refund;//退款/退货
    private LinearLayout ll_collection;//收藏
    private LinearLayout ll_attention;//关注
    private LinearLayout ll_foot_print;//足迹
    private LinearLayout ll_coupon;//优惠券
    private LinearLayout ll_all_order;//全部订单
    private LinearLayout ll_my_group_book;//我的拼团
    private LinearLayout ll_balance;// 余额
    private LinearLayout ll_advance;// //我的预定
    private LinearLayout ll_sevice;// //客服
    private LinearLayout ll_address;// //收货地址
    private ImageView iv_head;//头像
    private ImageView iv_mine_setting;//设置
    private TextView tv_login_registe;//登录
    private TextView tv_mine_title;//
    private ScrollView scrollView;
    private RecyclerView recyclerView;

    private TextView tv_wait_pay_num;//待付款的数量
    private TextView tv_waiting_send;//待发货的数量
    private TextView tv_waiting_reciever;//待发货的数量
    private TextView tv_waiting_comment;//待评论的数量
    private TextView tv_refund;//申请售后


    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
    }

    @Override
    protected int getInflate() {
        return R.layout.fragment_mine;
    }

//    @Override
//    protected int getRecyclerView() {
//        return 0;
//    }

    @Override
    protected ProgressLayout findProgressLayout(View view) {
        return null;
    }

    @Override
    protected void initRecyclerView(View v) {
        super.initRecyclerView(v);
        initView(v);
        setListen();
    }

    @Override
    protected LRecyclerView getRecyclerView(View view) {
        return null;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent = new Intent(getContext(), MyOrderActivity.class);
        if (v == iv_head || v == tv_login_registe) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(AccountSettingActivity.class);
            }

        }

        if (v == ll_all_order) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(MyOrderActivity.class);
            }
        }

        if (v == iv_mine_setting) {
            startActivity(SettingActivity.class);
        }

        if (v == ll_waiting_pay) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                intent.putExtra("position", 1);
                startActivity(intent);
            }
        }

        if (v == ll_waiting_send) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                intent.putExtra("position", 2);
                startActivity(intent);
            }
        }

        if (v == ll_waiting_reciever) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                intent.putExtra("position", 3);
                startActivity(intent);
            }
        }

        if (v == ll_waiting_comment) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                intent.putExtra("position", 4);
                startActivity(intent);
            }
        }

        if (v == ll_refund) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(AfterSalesOrderActivity.class);
            }
        }

        if (v == ll_collection) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                Intent intent1 = new Intent(getContext(), UserProductActivity.class);
                intent1.putExtra("position", 0);
                startActivity(intent1);
            }
        }

        if (v == ll_attention) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                Intent intent1 = new Intent(getContext(), UserProductActivity.class);
                intent1.putExtra("position", 1);
                startActivity(intent1);
            }
        }

        if (v == ll_foot_print) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                Intent intent1 = new Intent(getContext(), InviteFriendsActivity.class);
                intent1.putExtra("position", 2);
                startActivity(intent1);
            }
        }

        if (v == ll_coupon) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(UserCouponActivity.class);
            }
        }
        //拼团
        if (v == ll_my_group_book) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(MyGroupBookingActivity.class);
            }
        }
        //余额
        if (v == ll_balance) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
//                startActivity(BalanceActivity.class);
                startActivity(WalletActivity.class);// 钱包 modified by wubin at 200415
            }
        }

        if (v == ll_advance) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(MyAdvanceOrderActivity.class);
            }
        }

        if (v == ll_sevice) {
            getService();
        }

        if (v == ll_my_comment) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(MyCommentActivity.class);
            }
        }

        if (v == ll_address) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(AddressListActivity.class);
            }
        }
    }

    @Override
    protected RecyclerView.Adapter initAdapter() {
        return null;
    }

    @Override
    protected void reqFirst() {

    }

    @Override
    protected void reqMore() {

    }

    @Override
    protected void reReq() {

    }

    private DataAdapter adapter;

    private LinearLayout ll_my_comment;

    private void initView(View view) {
        ll_user_head = view.findViewById(R.id.ll_user_head);
        ll_collection = view.findViewById(R.id.ll_collection);
        ll_attention = view.findViewById(R.id.ll_attention);
        ll_foot_print = view.findViewById(R.id.ll_foot_print);
        ll_coupon = view.findViewById(R.id.ll_coupon);
        ll_waiting_pay = view.findViewById(R.id.ll_waiting_pay);
        ll_sevice = view.findViewById(R.id.ll_sevice);
        ll_address = view.findViewById(R.id.ll_address);
        ll_waiting_reciever = view.findViewById(R.id.ll_waiting_reciever);
        ll_waiting_comment = view.findViewById(R.id.ll_waiting_comment);
        ll_my_group_book = view.findViewById(R.id.ll_my_group_book);
        ll_waiting_send = view.findViewById(R.id.ll_waiting_send);
        ll_balance = view.findViewById(R.id.ll_balance);
        ll_advance = view.findViewById(R.id.ll_advance);
        ll_refund = view.findViewById(R.id.ll_refund);
        ll_all_order = view.findViewById(R.id.ll_all_order);
        ll_my_comment = view.findViewById(R.id.ll_my_comment);
        iv_head = view.findViewById(R.id.iv_head);
        iv_mine_setting = view.findViewById(R.id.iv_mine_setting);
        tv_login_registe = view.findViewById(R.id.tv_login_registe);
        tv_mine_title = view.findViewById(R.id.tv_mine_title);
        scrollView = view.findViewById(R.id.scrollView);

        tv_wait_pay_num = view.findViewById(R.id.tv_wait_pay_num);
        tv_waiting_send = view.findViewById(R.id.tv_waiting_send);
        tv_waiting_reciever = view.findViewById(R.id.tv_waiting_reciever);
        tv_waiting_comment = view.findViewById(R.id.tv_waiting_comment);
        tv_refund = view.findViewById(R.id.tv_refund);
        recyclerView = view.findViewById(R.id.recyclerView);

        GridLayoutManager manager = new GridLayoutManager(getContext(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerView.setLayoutManager(manager);
        adapter = new DataAdapter(getContext());
        recyclerView.setAdapter(adapter);
    }

    private void setListen() {
        tv_login_registe.setOnClickListener(this);
        iv_head.setOnClickListener(this);
        iv_mine_setting.setOnClickListener(this);
        ll_all_order.setOnClickListener(this);
        ll_waiting_pay.setOnClickListener(this);
        ll_waiting_send.setOnClickListener(this);
        ll_waiting_reciever.setOnClickListener(this);
        ll_waiting_comment.setOnClickListener(this);
        ll_collection.setOnClickListener(this);
        ll_attention.setOnClickListener(this);
        ll_foot_print.setOnClickListener(this);
        ll_coupon.setOnClickListener(this);
        ll_refund.setOnClickListener(this);
        ll_my_group_book.setOnClickListener(this);
        ll_balance.setOnClickListener(this);
        ll_advance.setOnClickListener(this);
        ll_sevice.setOnClickListener(this);
        ll_my_comment.setOnClickListener(this);
        ll_address.setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {

                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if (scrollY >= ll_user_head.getHeight() / 2) {
                        if (CommonUtils.isLogin()) {
                            tv_mine_title.setText(AppHolder.instance().getUser().getNickName());
                        }

                    } else {
                        tv_mine_title.setText("");
                    }
                }

            });
        }

        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                Product product = new Product();
                product.setGoodId(AppHolder.instance().getGlobalProList().get(position).getGoodsId());
                Bundle bundle = new Bundle();
                bundle.putSerializable("product", product);
                try {
                    A_Rutils.startActivity(getContext(), "com.ruitu.mall_98_1.product.activity.ProductDetailActivity", bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //初始化用户信息
    private void setData() {
        User user = AppHolder.instance().getUser();
        if (user != null) {
            tv_login_registe.setText(user.getNickName());
            if (!TextUtils.isEmpty(user.getDzf())) {
                if (Integer.parseInt(user.getDzf()) > 0) {
                    tv_wait_pay_num.setText(user.getDzf());
                    tv_wait_pay_num.setVisibility(View.VISIBLE);
                } else {
                    tv_wait_pay_num.setVisibility(View.GONE);
                }
            }

            if (!TextUtils.isEmpty(user.getDfh())) {
                if (Integer.parseInt(user.getDfh()) > 0) {
                    tv_waiting_send.setText(user.getDfh());
                    tv_waiting_send.setVisibility(View.VISIBLE);
                } else {
                    tv_waiting_send.setVisibility(View.GONE);
                }
            }

            if (!TextUtils.isEmpty(user.getDsh())) {
                if (Integer.parseInt(user.getDsh()) > 0) {
                    tv_waiting_reciever.setText(user.getDsh());
                    tv_waiting_reciever.setVisibility(View.VISIBLE);
                } else {
                    tv_waiting_reciever.setVisibility(View.GONE);
                }
            }
            if (!TextUtils.isEmpty(user.getYwc())) {
                if (Integer.parseInt(user.getYwc()) > 0) {
                    tv_waiting_comment.setText(user.getYwc());
                    tv_waiting_comment.setVisibility(View.VISIBLE);
                } else {
                    tv_waiting_comment.setVisibility(View.GONE);
                }
            }
            if (!TextUtils.isEmpty(user.getTk())) {
                if (Integer.parseInt(user.getTk()) > 0) {
                    tv_refund.setText(user.getTk());
                    tv_refund.setVisibility(View.VISIBLE);
                } else {
                    tv_refund.setVisibility(View.GONE);
                }
            }

            Glide.with(getContext()).load(Config.BASE_URL + AppHolder.instance().getUser().getImageUrl()).apply(Arad.opts_circle).into(iv_head);
        } else {
            tv_login_registe.setText("点击登录");
            Glide.with(getContext()).load(R.mipmap.default_img).apply(Arad.opts_circle).into(iv_head);
            tv_wait_pay_num.setVisibility(View.GONE);
            tv_waiting_send.setVisibility(View.GONE);
            tv_waiting_reciever.setVisibility(View.GONE);
            tv_waiting_comment.setVisibility(View.GONE);
            tv_refund.setVisibility(View.GONE);
            JPushInterface.setAlias(Arad.app, 0, "1111111110");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        String tel = Arad.preferences.getString("tel");
        String psw = Arad.preferences.getString("psw");

        String openId = Arad.preferences.getString("openId");
        String type = Arad.preferences.getString("type");

        if (!TextUtils.isEmpty(tel) && !TextUtils.isEmpty(psw)) {
            setLogin(tel, MD5Util.md5String(psw));
        } else if (!TextUtils.isEmpty(openId) && !TextUtils.isEmpty(type)) {
            setThirdLogin(openId, type);
        } else {
            setData();
        }

    }

    private void setLogin(String tel, String psw) {
        APIRetrofit.getDefault().login(tel, psw, "1", "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult<User>>() {
                    @Override
                    public void onError(Throwable e) {
                        Logg.i(e.toString());
//                        ToastUtils.showShort("登录失败");
                    }

                    @Override
                    public void onNext(BaseResult<User> userBaseResult) {
                        if (userBaseResult.isSuccess()) {
                            AppHolder.instance().setUser(userBaseResult.getData());
                            setData();
                            Arad.bus.post(new EventModel(18110900));
                        }
                    }
                });
    }

    private void setThirdLogin(String u, String t) {
        APIRetrofit.getDefault().quickLogin(u, t)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult<User>>() {
                    @Override
                    public void onError(Throwable e) {
                        Logg.i(e.toString());
                    }

                    @Override
                    public void onNext(BaseResult<User> userBaseResult) {
                        if (userBaseResult.isSuccess()) {
                            AppHolder.instance().setUser(userBaseResult.getData());
                            setData();
                            Arad.bus.post(new EventModel(18110900));
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setLogOut(EventModel eventModel) {
        if (eventModel.getEventCode() == 180102500) {
            setData();
        }

        if (eventModel.getEventCode() == 18122751) {
            adapter.setDataList(AppHolder.instance().getGlobalProList());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销EventBus
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    private void getService() {
        showProgress();
        APIRetrofit.getDefault().getPlatFormInfo().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<Service>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        ToastUtils.showShort("获取客服消息失败");
                    }

                    @Override
                    public void onNext(BaseResult<Service> serviceBaseResult) {
                        hideProgress();
                        if (serviceBaseResult.isSuccess()) {
                            showService(serviceBaseResult.getData());
                        } else {
                            ToastUtils.showShort(serviceBaseResult.getMsg());
                        }
                    }
                });
    }

    private void showService(final Service data) {
        AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
        View view = View.inflate(getContext(), R.layout.dialog_service, null);
        TextView tv_service_tel = view.findViewById(R.id.tv_service_tel);
        TextView tv_service_qq1 = view.findViewById(R.id.tv_service_qq1);
        TextView tv_service_qq2 = view.findViewById(R.id.tv_service_qq2);
        tv_service_tel.setText(data.getTelPhone());
        tv_service_qq1.setText(data.getQq1());
        tv_service_qq2.setText(data.getQq2());

        tv_service_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.getTelPhone()));
                startActivity(intent);
            }
        });

        tv_service_qq1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardUtils.copyText(data.getQq1());
                ToastUtils.showShort("QQ1已复制到剪贴板");
            }
        });
        tv_service_qq2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardUtils.copyText(data.getQq2());
                ToastUtils.showShort("QQ2已复制到剪贴板");
            }
        });

        alertDialog.setView(view);
        alertDialog.show();
    }
}
